﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VCommons;
using System.Web;
using System.IO;

namespace FileCache
{
    /// <summary>
    /// 缓存对象操作类
    /// </summary>
    public class CacheExtension
    {
        /// <summary>
        /// 缓存日期（最后一次从文件读到的时间）
        /// </summary>
        public static DateTime LastModifyDate { get; private set; }
        /// <summary>
        /// 读缓存对象（前台用）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static List<T> LoadCache<T>(string cacheName) where T : class
        {

            if (File.Exists(ReturnCachePath(cacheName)))
            {
                if (LastModifyDate == DateTime.MinValue)
                    LastModifyDate = File.GetLastWriteTime(ReturnCachePath(cacheName));
                var lastTime = File.GetLastWriteTime(ReturnCachePath(cacheName));
                //判断是否存在cache，并且最后修改时间是否为物理文件的最扣保存时间，如果是，读缓存，如果否，读文件
                if (DataCache.GetCache(cacheName) != null && LastModifyDate.Equals(lastTime))
                {
                    return (List<T>)DataCache.GetCache(cacheName);
                }
                else //缓存物理文件有更新，需要重新写Cache
                {
                    List<T> entityList = (List<T>)SerializationHelper.Load(typeof(List<T>), ReturnCachePath(cacheName));
                    DataCache.RemoveCache(cacheName);
                    DataCache.SetCache(cacheName, entityList);
                    LastModifyDate = File.GetLastWriteTime(ReturnCachePath(cacheName));//更新缓存有效时间
                    return entityList;
                }
            }
            else //如果不存在缓存物理文件，则直接返回NULL，表示缓存没有生成，直接由调用层返回结果，不走缓存
            {

                return null;
            }

        }
        /// <summary>
        /// 写缓存对象（后用用）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="filename"></param>
        public static void SaveCache<T>(string cacheName, IEnumerable<T> entity) where T : class
        {
            /// <summary>
            /// 线程锁
            /// </summary>
            object lockHelper = new object();
            lock (lockHelper)
            {
                SerializationHelper.Save(entity.ToList(), ReturnCachePath(cacheName));
                //文件更新后，则删除cache
                DataCache.RemoveCache(cacheName);
            }
        }

        /// <summary>
        /// 返回缓存文件地址[默认存储在D盘Caches目录]
        /// </summary>
        /// <param name="cacheName"></param>
        /// <returns></returns>
        static string ReturnCachePath(string cacheName)
        {
            //HttpContext context = HttpContext.Current;
            //if (context != null)
            //{
            //    cacheName = context.Server.MapPath(string.Format("/Caches/{0}", cacheName));
            //}
            //else
            //{1
            //    cacheName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Caches\{0}", cacheName);
            //}
            //return cacheName;
            if (!Directory.Exists("E://Caches"))
                Directory.CreateDirectory("E://Caches");
            return string.Format("E://Caches//{0}", cacheName);
        }

    }
}


